#coding:utf-8
__author__ = 'hl'

import wx
import wx.grid as grd

class GridWithCheckBoxOnly(grd.Grid):
    def __init__(self,parent,id,size=wx.DefaultSize):
        grd.Grid.__init__(self,parent,id,size=size)

        #绑定事件
        self.Bind(grd.EVT_GRID_CELL_LEFT_CLICK,self.OnMouse)
        self.Bind(grd.EVT_GRID_SELECT_CELL,self.OnSelectedCell)
        self.Bind(grd.EVT_GRID_EDITOR_CREATED,self.OnEditorCreated)
        self.selectedRows = []
        



    def SetTable(self,table,takeOwnership=False,selmode=wx.grid.Grid.SelectRows):
        grd.Grid.SetTable(self,table,takeOwnership,selmode)
        self.__SetFirstColAttr()
        self.SetRowLabelSize(1)


    def __SetFirstColAttr(self):
        attr = grd.GridCellAttr()
        attr.SetRenderer(grd.GridCellBoolRenderer())
        attr.SetEditor(grd.GridCellBoolEditor())
        self.SetAllCellAttr({0:attr})

    #为网格设置属性,attrDir为字典类型，Key:列的索引，Value：属性
    def SetAllCellAttr(self,attrDir):
        for col in attrDir.keys():
            self.SetColAttr(col,attrDir.get(col))

    def OnMouse(self,evt):
        if evt.Col == 0:
            wx.CallLater(100,self.toggleCheckBox)
        evt.Skip()

    def toggleCheckBox(self):
        self.cb.Value = not self.cb.Value
        self.StatisticsSelectedRows()

    def OnEditorCreated(self,evt):
        if evt.Col ==0:
            self.cb = evt.Control
            self.cb.Bind(wx.EVT_CHECKBOX,self.OnCheckBox)
        evt.Skip()

    def OnCheckBox(self,evt):
        self.StatisticsSelectedRows()

    def OnSelectedCell(self,evt):
        if evt.Col ==0:
            wx.CallAfter(self.EnableCellEditControl)
        evt.Skip()

    def StatisticsSelectedRows(self):
        try:
            if self.cb.IsChecked():
                self.selectedRows.append(self.GridCursorRow)
            else:
                self.selectedRows.remove(self.GridCursorRow)
        except:
            pass

    def AbandonRowHead(self):
        self.RowLabelSize=0

    def SetGridColsSize(self,width):
        if width >0:
            self.SetDefaultColSize(width,True)

        self.SetColSize(0,22)


